<!-- templates/products/productlist.html -->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>商品管理 - 商店进销存管理系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 阿里云 CDN -->
  <link href="https://unpkg.com/element-plus@2.4.3/dist/index.min.css" rel="stylesheet">
  <script src="https://unpkg.com/element-plus@2.4.3/dist/index.full.min.js"></script>

  <!-- 引入 Toastify CSS 和 JS -->
  <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#0FC6C2',
            success: '#00B42A',
            warning: '#FF7D00',
            danger: '#F53F3F',
            info: '#86909C'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }

      .sidebar-item {
        @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
      }

      .sidebar-item.active {
        @apply bg-primary/10 text-primary border-l-4 border-primary;
      }

      .card-shadow {
        @apply shadow-md hover:shadow-lg transition-shadow duration-300;
      }
    }
  </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
  <div class="container mx-auto px-4 py-3 flex justify-between items-center">
    <div class="flex items-center space-x-2">
      <i class="fa fa-cubes text-primary text-2xl"></i>
      <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
    </div>

    <div class="flex items-center space-x-6">
      <div class="relative">
        <input type="text" placeholder="搜索..."
               class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
      </div>

      <div class="flex items-center space-x-4">
        <button class="text-gray-600 hover:text-primary transition-colors">
          <i class="fa fa-bell-o text-xl"></i>
        </button>
        <button class="text-gray-600 hover:text-primary transition-colors">
          <i class="fa fa-cog text-xl"></i>
        </button>
        <div class="flex items-center space-x-2 cursor-pointer">
          <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
          <span class="text-gray-700">管理员</span>
        </div>
      </div>
    </div>
  </div>
</header>

<div class="flex flex-1 overflow-hidden">
  <!-- 侧边栏导航 -->
  <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
    <nav class="py-4">
      <div class="px-4 mb-4">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
      </div>

      <a href="../../index.html" class="sidebar-item" data-path="../../index.html">
        <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
        <span>仪表盘</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
      </div>

      <a href="../products/list.html" class="sidebar-item active" data-path="../products/list.html">
        <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
        <span>商品管理</span>
      </a>

      <a href="../categories/list.html" class="sidebar-item" data-path="../categories/list.html">
        <i class="fa fa-th-large w-5 h-5 mr-3"></i>
        <span>类别管理</span>
      </a>

      <a href="../suppliers/list.html" class="sidebar-item">
        <i class="fa fa-truck w-5 h-5 mr-3"></i>
        <span>供应商管理</span>
      </a>

      <a href="../customers/list.html" class="sidebar-item">
        <i class="fa fa-users w-5 h-5 mr-3"></i>
        <span>客户管理</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
      </div>

      <a href="../inventory/warehouse.html" class="sidebar-item">
        <i class="fa fa-archive w-5 h-5 mr-3"></i>
        <span>仓库管理</span>
      </a>

      <a href="../inventory/stock.html" class="sidebar-item">
        <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
        <span>库存查询</span>
      </a>

      <a href="../inventory/instock.html" class="sidebar-item">
        <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
        <span>入库管理</span>
      </a>

      <a href="../inventory/outstock.html" class="sidebar-item">
        <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
        <span>出库管理</span>
      </a>

      <a href="../inventory/transfer.html" class="sidebar-item">
        <i class="fa fa-exchange w-5 h-5 mr-3"></i>
        <span>转仓管理</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
      </div>

      <a href="../statistics/sales.html" class="sidebar-item">
        <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
        <span>销售统计</span>
      </a>

      <a href="../statistics/inventory.html" class="sidebar-item">
        <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
        <span>库存分析</span>
      </a>

      <div class="px-4 mt-6 mb-2">
        <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
      </div>

      <a href="../system/users.html" class="sidebar-item">
        <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
        <span>用户管理</span>
      </a>

      <a href="../system/roles.html" class="sidebar-item">
        <i class="fa fa-shield w-5 h-5 mr-3"></i>
        <span>角色权限</span>
      </a>

      <a href="../system/logs.html" class="sidebar-item">
        <i class="fa fa-history w-5 h-5 mr-3"></i>
        <span>操作日志</span>
      </a>
    </nav>
  </aside>

  <!-- 主内容区域 -->
  <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
    <div class="container mx-auto">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">商品管理</h2>
        <p class="text-gray-500 mt-1">管理商店的所有商品信息</p>
      </div>

      <!-- 操作按钮 -->
      <div class="mb-4 flex justify-between items-center">
        <button class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center" id="addProductBtn">
          <i class="fa fa-plus mr-2"></i> 添加商品
        </button>
      </div>

      <!-- 筛选表单 -->
      <div class="mb-4 bg-white rounded-lg p-4 card-shadow">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">商品名称</label>
            <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入商品名称">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">商品类别</label>
            <select id="filterCategory" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
              <option value="">全部类别</option>
              <!-- 类别选项将通过JS动态插入 -->
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">商品状态</label>
            <select id="filterStatus" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
              <option value="">全部状态</option>
              <option value="active">上架</option>
              <option value="inactive">下架</option>
            </select>
          </div>
          <div class="flex items-end space-x-2">
            <button id="filterBtn" class="flex-1 bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center justify-center">
              <i class="fa fa-filter mr-2"></i> 筛选
            </button>
            <button id="resetFilterBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
              重置
            </button>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="bg-white rounded-xl p-6 card-shadow">
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead>
            <tr class="border-b border-gray-200">
              <th class="py-3 text-left text-sm font-medium text-gray-500">商品编号</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">商品名称</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">价格</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">库存</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">状态</th>
              <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
            </tr>
            </thead>
            <tbody id="productTable">
            <!-- 数据将通过JS动态渲染 -->
            </tbody>
          </table>
        </div>

        <!-- 分页控件 -->
        <div class="mt-6 flex justify-between items-center">
          <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
          <div class="flex space-x-1" id="paginationControls">
            <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 disabled:opacity-50" disabled>
              <i class="fa fa-chevron-left"></i>
            </button>
            <button class="px-3 py-1 border border-primary bg-primary text-white rounded-md">1</button>
            <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">2</button>
            <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">3</button>
            <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50">
              <i class="fa fa-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>

<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
  <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
    <p>© 2025 商店进销存管理系统 - 版权所有</p>
  </div>
</footer>

<!-- 商品添加模态框 (动态创建) -->
<div id="productModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- 编辑商品模态框 (添加到productModal之后) -->
<div id="editProductModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- JavaScript -->
<script>
  // 侧边栏切换（保持原有功能）
  const toggleSidebar = () => {
    const sidebar = document.querySelector('aside');
    sidebar.classList.toggle('w-64');
    sidebar.classList.toggle('w-20');

    const sidebarTexts = document.querySelectorAll('aside span');
    sidebarTexts.forEach(text => {
      text.classList.toggle('hidden');
    });
  };

  // 页面加载完成后初始化
  document.addEventListener('DOMContentLoaded', () => {
    initSidebarNavigation();
    setCurrentPageActive();
    loadProducts(); // 加载商品数据
    loadCategories();
    // 筛选按钮点击事件
    document.getElementById('filterBtn').addEventListener('click', applyFilter);

    // 重置筛选按钮点击事件
    document.getElementById('resetFilterBtn').addEventListener('click', resetFilter);

    // 绑定添加商品按钮事件
    document.getElementById('addProductBtn').addEventListener('click', showAddProductForm);

    // 绑定编辑商品按钮事件
    document.addEventListener('click', (e) => {
      if (e.target.closest('.fa-pencil')) {
        const productId = parseInt(e.target.closest('button').parentElement.parentElement.querySelector('td:first-child').textContent);
        editProduct(productId);
      }
    });
  });

  let categories = []; // 全局变量存储商品类别数据
  // 全局变量存储当前编辑的商品ID
  let currentEditingProductId = null;
  // 全局筛选参数
  let filterParams = {
    name: '',
    categoryId: '',
    status: ''
  };


  /**
   * 应用筛选条件
   */
  const applyFilter = () => {
    // 获取筛选表单的值
    filterParams = {
      name: document.getElementById('filterName').value.trim(),
      categoryId: document.getElementById('filterCategory').value,
      status: document.getElementById('filterStatus').value
    };

    // 从第一页开始加载数据
    loadProducts(0);
  };

  /**
   * 重置筛选条件
   */
  const resetFilter = () => {
    // 重置表单
    document.getElementById('filterName').value = '';
    document.getElementById('filterCategory').value = '';
    document.getElementById('filterStatus').value = '';

    // 重置筛选参数
    filterParams = {
      name: '',
      categoryId: '',
      status: ''
    };

    // 从第一页开始加载数据
    loadProducts(0);
  };

  /**
   * 加载商品类别数据
   */
  const loadCategories = () => {
    fetch('../categories.json')
            .then(response => {
              if (!response.ok) {
                throw new Error(`获取类别数据失败: 状态码 ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              if (apiResponse.code === '200' && apiResponse.data && apiResponse.data.content) {
                categories = apiResponse.data.content;
                console.log('类别数据加载成功:', categories);

                // 填充筛选器的类别选项
                const filterCategory = document.getElementById('filterCategory');
                categories.forEach(category => {
                  const option = document.createElement('option');
                  option.value = category.categoryId;
                  option.textContent = category.categoryName;
                  filterCategory.appendChild(option);
                });
              } else {
                throw new Error(apiResponse.message || '获取类别数据失败');
              }
            })
            .catch(error => {
              console.error('加载类别数据失败:', error);
              // 可以选择显示错误提示或使用默认类别
            });
  };


  /**
   * 显示添加商品表单（包含类别选择）
   */
  const showAddProductForm = () => {
    const modal = document.getElementById('productModal');
    modal.classList.remove('hidden');

    const formContainer = document.createElement('div');
    formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
    formContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-800">添加新商品</h3>
      <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('productModal').classList.add('hidden')">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <form id="addProductForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="productName">商品名称</label>
        <input type="text" id="productName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="categoryId">商品类别</label>
        <select id="categoryId" name="categoryId" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
          <option value="">请选择类别</option>
          <!-- 类别选项将通过JS动态插入 -->
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="productPrice">价格</label>
        <input type="number" id="productPrice" name="price" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="productStock">库存</label>
        <input type="number" id="productStock" name="stock" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="productStatus">状态</label>
        <select id="productStatus" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
          <option value="active">上架</option>
          <option value="inactive">下架</option>
        </select>
      </div>
      <div class="flex justify-end space-x-3 mt-6">
        <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('productModal').classList.add('hidden')">取消</button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">添加商品</button>
      </div>
    </form>
  `;

    modal.innerHTML = '';
    modal.appendChild(formContainer);

    // 动态插入类别选项
    const categorySelect = document.getElementById('categoryId');
    if (categories.length > 0) {
      categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.categoryId;
        option.textContent = category.categoryName;
        categorySelect.appendChild(option);
      });
    } else {
      // 类别数据加载失败时的提示
      const option = document.createElement('option');
      option.value = '';
      option.textContent = '类别数据加载失败';
      option.disabled = true;
      categorySelect.appendChild(option);
    }

    // 表单提交事件
    document.getElementById('addProductForm').addEventListener('submit', (e) => {
      e.preventDefault();
      addProduct();
    });
  };

  /**
   * 添加商品到系统（包含类别ID）
   */
  const addProduct = () => {
    // 获取表单数据（包含categoryId）
    const formData = {
      productName: document.getElementById('productName').value,
      categoryId: document.getElementById('categoryId').value, // 新增类别ID
      productPrice: parseFloat(document.getElementById('productPrice').value),
      productStock: parseInt(document.getElementById('productStock').value),
      productStatus: document.getElementById('productStatus').value
    };

    // 验证类别是否选择
    if (!formData.categoryId) {
      alert('请选择商品类别');
      return;
    }

    // 显示加载状态
    const submitButton = document.querySelector('#addProductForm button[type="submit"]');
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

    // 调用API
    fetch('../product.json', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              console.log('添加商品API响应:', apiResponse);

              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '添加商品';

              // 处理响应
              if (apiResponse) {
                Toastify({
                  text: "商品添加成功",
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#4CAF50",
                }).showToast();
                // 关闭表单
                document.getElementById('productModal').classList.add('hidden');
                // 刷新商品列表
                loadProducts();
              } else {
                const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '添加失败：未知错误';
                alert(errorMsg);
              }
            })
            .catch(error => {
              console.error('添加商品失败:', error);
              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '添加商品';
              // 显示错误信息
              alert('添加商品失败: ' + error.message);
            });
  };

  /**
   * 从后端API加载商品数据（支持筛选）
   */
  let currentPage = 0; // 保存当前页码（后端从0开始）
  const loadProducts = (page = 0) => {
    const productTable = document.getElementById('productTable');
    const paginationInfo = document.getElementById('paginationInfo');
    const paginationControls = document.getElementById('paginationControls');

    // 显示加载中状态
    productTable.innerHTML = `
    <tr>
      <td colspan="6" class="py-4 text-center">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        <p class="mt-2 text-gray-600">加载商品数据中...</p>
      </td>
    </tr>
  `;

    // 构建筛选参数
    const queryParams = new URLSearchParams({
      page: page,
      size: 10,
      ...(filterParams.name && { name: filterParams.name }),
      ...(filterParams.categoryId && { categoryId: filterParams.categoryId }),
      ...(filterParams.status && { status: filterParams.status })
    });

    // 调用后端API获取商品数据（添加筛选参数）
    fetch(`../product.json?${queryParams}`)
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              console.log('API响应数据:', apiResponse);
              productTable.innerHTML = '';

              // 验证响应结构
              if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                throw new Error(apiResponse?.message || 'API响应失败');
              }

              // 解构数据
              const { content: products, totalElements, totalPages, pageable } = apiResponse.data;
              const currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

              // 更新分页信息
              const displayPage = currentPage + 1;
              paginationInfo.textContent = `共 ${totalElements} 条记录，当前第 ${displayPage} 页`;
              updatePaginationControls(totalPages, displayPage);

              // 处理无数据情况
              if (products.length === 0) {
                productTable.innerHTML = `
          <tr>
            <td colspan="6" class="py-4 text-center text-gray-500">没有找到符合条件的商品数据</td>
          </tr>
        `;
                return;
              }

              // 过滤有效数据（确保有productId）
              const validProducts = products.filter(product =>
                      product && typeof product === 'object' && product.productId !== undefined
              );

              if (validProducts.length === 0) {
                throw new Error('所有商品数据均无效');
              }

              // 渲染商品数据
              validProducts.forEach(product => {
                const row = document.createElement('tr');
                row.className = 'border-b border-gray-100 hover:bg-gray-50';

                // 从API数据中提取字段（含默认值处理）
                const id = product.productId;
                const name = product.productName || '未知名称';
                const price = product.productPrice !== null && product.productPrice !== undefined ? product.productPrice : 0;
                const stock = product.productStock !== null && product.productStock !== undefined ? product.productStock : 0;
                const status = product.productStatus || 'active';

                // 状态显示转换
                const statusText = status === 'active' ?
                        '<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">上架</span>' :
                        '<span class="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-500">下架</span>';

                row.innerHTML = `
          <td class="py-3 text-sm text-gray-600">${id}</td>
          <td class="py-3 text-sm text-gray-600">${name}</td>
          <td class="py-3 text-sm text-gray-600">¥${price.toFixed(2)}</td>
          <td class="py-3 text-sm text-gray-600">${stock}</td>
          <td class="py-3 text-sm text-gray-600">${statusText}</td>
          <td class="py-3 text-sm text-gray-600">
            <button class="text-primary mr-2" onclick="editProduct(${id})">
              <i class="fa fa-pencil"></i> 编辑
            </button>
            <button class="text-danger" onclick="deleteProduct(${id})">
              <i class="fa fa-trash"></i> 删除
            </button>
          </td>
        `;
                productTable.appendChild(row);
              });
            })
            .catch(error => {
              console.error('加载商品数据失败:', error);
              productTable.innerHTML = `
        <tr>
          <td colspan="6" class="py-4 text-center text-red-500">
            <i class="fa fa-exclamation-circle mr-2"></i> 加载商品数据失败，请稍后重试
          </td>
        </tr>
      `;

              Toastify({
                text: `加载商品数据失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
              }).showToast();
            });
  };

  /**
   * 更新分页控件
   */
  const updatePaginationControls = (totalPages, currentPage) => {
    const controls = document.getElementById('paginationControls');
    controls.innerHTML = '';

    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
    prevBtn.disabled = currentPage === 1;
    prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
    prevBtn.addEventListener('click', () => {
      if (currentPage > 1) {
        loadProducts(currentPage - 2); // 转换为后端页码（前端页码-1）
      }
    });
    controls.appendChild(prevBtn);

    // 页码按钮 (显示当前页及前后两页)
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    for (let i = startPage; i <= endPage; i++) {
      const pageBtn = document.createElement('button');
      pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
      pageBtn.textContent = i;
      pageBtn.addEventListener('click', () => {
        loadProducts(i - 1); // 转换为后端页码（前端页码-1）
      });
      controls.appendChild(pageBtn);
    }

    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
    nextBtn.addEventListener('click', () => {
      if (currentPage < totalPages) {
        loadProducts(currentPage); // 转换为后端页码（前端页码-1）
      }
    });
    controls.appendChild(nextBtn);
  };
  /**
   * 显示消息提示（替代ElMessage）
   */
  const showMessage = (message, type = 'success') => {
    if (window.ElementPlus && window.ElementPlus.ElMessage) {
      // 使用Element Plus的消息提示
      window.ElementPlus.ElMessage({
        message,
        type,
        duration: 3000
      });
    } else {
      // 备选方案：使用原生alert
      alert(`${type === 'success' ? '成功' : '错误'}: ${message}`);
    }
  };

  /**
   * 加载指定页码的商品数据（新增函数，处理分页请求）
   */
  const loadProductsWithPage = (pageNumber) => {
    // 实际项目中应传递page参数到API
    // 示例：fetch(`/product?page=${pageNumber-1}&size=10`)
    // 此处仅模拟页码切换效果
    const productTable = document.getElementById('productTable');
    productTable.innerHTML = `
    <tr>
      <td colspan="6" class="py-4 text-center">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        <p class="mt-2 text-gray-600">加载第 ${pageNumber} 页数据中...</p>
      </td>
    </tr>
  `;

    // 模拟延迟加载（实际项目中删除此定时器，直接调用API）
    setTimeout(() => {
      // 注意：实际项目中应传递page参数（后端从0开始）
      // loadProducts(pageNumber - 1);
      loadProducts(); // 临时用全量加载模拟
    }, 500);
  };

  /**
   * 加载商品详情
   */
  const fetchProductDetails = async (productId) => {
    try {
      const response = await fetch(`../product.json/${productId}`);
      if (!response.ok) {
        throw new Error(`获取商品详情失败: 状态码 ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('获取商品详情失败:', error);
      Toastify({
        text: `获取商品详情失败: ${error.message}`,
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      throw error;
    }
  };
  /**
   * 显示编辑商品表单
   */
  const showEditProductForm = (productId) => {
    currentEditingProductId = productId;
    const modal = document.getElementById('editProductModal');
    modal.classList.remove('hidden');

    const formContainer = document.createElement('div');
    formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
    formContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-800">编辑商品</h3>
      <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('editProductModal').classList.add('hidden')">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <form id="editProductForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editProductName">商品名称</label>
        <input type="text" id="editProductName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editCategoryId">商品类别</label>
        <select id="editCategoryId" name="categoryId" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
          <option value="">请选择类别</option>
          <!-- 类别选项将通过JS动态插入 -->
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editProductPrice">价格</label>
        <input type="number" id="editProductPrice" name="price" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editProductStock">库存</label>
        <input type="number" id="editProductStock" name="stock" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editProductStatus">状态</label>
        <select id="editProductStatus" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
          <option value="active">上架</option>
          <option value="inactive">下架</option>
        </select>
      </div>
      <div class="flex justify-end space-x-3 mt-6">
        <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('editProductModal').classList.add('hidden')">取消</button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">保存修改</button>
      </div>
    </form>
  `;

    modal.innerHTML = '';
    modal.appendChild(formContainer);

    // 动态插入类别选项
    const categorySelect = document.getElementById('editCategoryId');
    if (categories.length > 0) {
      categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.categoryId;
        option.textContent = category.categoryName;
        categorySelect.appendChild(option);
      });
    } else {
      const option = document.createElement('option');
      option.value = '';
      option.textContent = '类别数据加载失败';
      option.disabled = true;
      categorySelect.appendChild(option);
    }

    // 加载商品详情并填充表单
    fetchProductDetails(productId)
            .then(product => {
              document.getElementById('editProductName').value = product.productName || '';
              document.getElementById('editProductPrice').value = product.productPrice || 0;
              document.getElementById('editProductStock').value = product.productStock || 0;
              document.getElementById('editProductStatus').value = product.productStatus || 'active';

              // 选中对应的类别
              if (product.categoryId && categorySelect.options) {
                for (let i = 0; i < categorySelect.options.length; i++) {
                  if (categorySelect.options[i].value === product.categoryId.toString()) {
                    categorySelect.options[i].selected = true;
                    break;
                  }
                }
              }
            })
            .catch(() => {
              // 加载失败时清空表单
              document.getElementById('editProductName').value = '';
              document.getElementById('editProductPrice').value = 0;
              document.getElementById('editProductStock').value = 0;
              document.getElementById('editProductStatus').value = 'active';
            });

    // 表单提交事件
    document.getElementById('editProductForm').addEventListener('submit', (e) => {
      e.preventDefault();
      updateProduct();
    });
  };

  /**
   * 更新商品信息
   */
  const updateProduct = () => {
    if (!currentEditingProductId) {
      Toastify({
        text: "编辑失败：未选择商品",
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      return;
    }

    // 获取表单数据
    const formData = {
      productId: currentEditingProductId,
      productName: document.getElementById('editProductName').value,
      categoryId: document.getElementById('editCategoryId').value,
      productPrice: parseFloat(document.getElementById('editProductPrice').value),
      productStock: parseInt(document.getElementById('editProductStock').value),
      productStatus: document.getElementById('editProductStatus').value
    };

    // 验证类别是否选择
    if (!formData.categoryId) {
      Toastify({
        text: "请选择商品类别",
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
      }).showToast();
      return;
    }

    // 显示加载状态
    const submitButton = document.querySelector('#editProductForm button[type="submit"]');
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

    // 调用API
    fetch(`../product.json/${formData.productId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
              }
              return response.json();
            })
            .then(apiResponse => {
              console.log('更新商品API响应:', apiResponse);

              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '保存修改';

              // 处理响应
              if (apiResponse) {
                Toastify({
                  text: "商品更新成功",
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#4CAF50",
                }).showToast();
                // 关闭表单
                document.getElementById('editProductModal').classList.add('hidden');
                // 刷新商品列表
                loadProducts();
              } else {
                const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '更新失败：未知错误';
                Toastify({
                  text: errorMsg,
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#f44336",
                }).showToast();
              }
            })
            .catch(error => {
              console.error('更新商品失败:', error);
              // 恢复按钮状态
              submitButton.disabled = false;
              submitButton.innerHTML = '保存修改';
              // 显示错误信息
              Toastify({
                text: `更新商品失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
              }).showToast();
            });
  };

  /**
   * 编辑商品
   */
  const editProduct = (productId) => {
    if (!categories.length) {
      // 类别数据未加载时先加载
      loadCategories().then(() => {
        showEditProductForm(productId);
      });
    } else {
      showEditProductForm(productId);
    }
  };
  /**
   * 删除商品
   */
  const deleteProduct = (productId) => {
    if (confirm('确定要删除这个商品吗？此操作不可恢复。')) {
      // 找到触发事件的按钮（修复event未定义的问题）
      const deleteBtn = event?.target?.closest('button') ||
              document.querySelector(`button[onclick="deleteProduct(${productId})"]`);

      if (deleteBtn) {
        deleteBtn.disabled = true;
        deleteBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 处理中...';
      }

      fetch(`../product.json/${productId}`, {
        method: 'DELETE'
      })
              .then(response => {
                if (response.ok) {
                  Toastify({
                    text: "商品删除成功",
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#4CAF50",
                  }).showToast();

                  loadProducts();
                } else {
                  throw new Error(`删除失败: ${response.statusText}`);
                }
              })
              .catch(error => {
                console.error('删除商品失败:', error);
                Toastify({
                  text: `商品删除失败: ${error.message}`,
                  duration: 3000,
                  gravity: "top",
                  position: "right",
                  backgroundColor: "#f44336",
                }).showToast();
              })
              .finally(() => {
                if (deleteBtn) {
                  deleteBtn.disabled = false;
                  deleteBtn.innerHTML = '<i class="fa fa-trash"></i> 删除';
                }
              });
    }
  };
  /**
   * 初始化侧边栏导航
   */
  const initSidebarNavigation = () => {
    const sidebarItems = document.querySelectorAll('.sidebar-item');

    sidebarItems.forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();

        const path = item.getAttribute('data-path');
        if (!path) return;

        // 更新激活状态
        updateActiveItem(item);

        // 显示加载指示器
        showPageLoader();

        // 使用平滑过渡加载新页面
        setTimeout(() => {
          window.location.href = path;
        }, 300); // 动画持续时间
      });
    });
  };

  /**
   * 更新激活菜单项
   */
  const updateActiveItem = (activeItem) => {
    document.querySelectorAll('.sidebar-item').forEach(item => {
      item.classList.remove('active');
    });
    activeItem.classList.add('active');
  };

  /**
   * 设置当前页面菜单项为激活状态
   */
  const setCurrentPageActive = () => {
    const currentPath = window.location.pathname;
    const sidebarItems = document.querySelectorAll('.sidebar-item');

    sidebarItems.forEach(item => {
      const itemPath = item.getAttribute('data-path');
      if (itemPath && currentPath.endsWith(itemPath)) {
        updateActiveItem(item);
        return;
      }
    });
  };

  /**
   * 显示页面加载指示器
   */
  const showPageLoader = () => {
    const mainContent = document.querySelector('main');

    // 创建加载指示器元素
    const loader = document.createElement('div');
    loader.className = 'fixed inset-0 bg-white bg-opacity-80 flex items-center justify-center z-50 transition-opacity duration-300';
    loader.innerHTML = `
        <div class="text-center">
          <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
          <p class="mt-4 text-gray-600">加载中...</p>
        </div>
      `;

    // 添加到页面
    document.body.appendChild(loader);

    // 300ms后移除（与导航延迟匹配）
    setTimeout(() => {
      loader.classList.add('opacity-0');
      setTimeout(() => {
        document.body.removeChild(loader);
      }, 300);
    }, 300);
  };
</script>
</body>

</html>